package com.bootdo.fx.service.impl;

import com.bootdo.fx.dao.UserFundsInfoDao;
import com.bootdo.fx.domain.UserFundsInfoDO;
import com.bootdo.fx.domain.UserInfoDO;
import com.bootdo.fx.service.UserFundsInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.bootdo.fx.dao.UserWithdrawDao;
import com.bootdo.fx.domain.UserWithdrawDO;
import com.bootdo.fx.service.UserWithdrawService;
import org.springframework.transaction.annotation.Transactional;


@Service
public class UserWithdrawServiceImpl implements UserWithdrawService {
	@Autowired
	private UserWithdrawDao userWithdrawDao;

	@Autowired
	private UserFundsInfoDao userFundsInfoDao;
	
	@Override
	public UserWithdrawDO get(Long withdrawId){
		return userWithdrawDao.get(withdrawId);
	}
	
	@Override
	public List<UserWithdrawDO> list(Map<String, Object> map){
		return userWithdrawDao.list(map);
	}
	
	@Override
	public int count(Map<String, Object> map){
		return userWithdrawDao.count(map);
	}
	
	@Override
	public int save(UserWithdrawDO userWithdraw){
		return userWithdrawDao.save(userWithdraw);
	}
	
	@Override
	public int update(UserWithdrawDO userWithdraw){
		return userWithdrawDao.update(userWithdraw);
	}
	
	@Override
	@Transactional
	public int remove(Long withdrawId){
		UserWithdrawDO u = userWithdrawDao.get(withdrawId);
		Map<String,Object> map = new HashMap<>();
		map.put("userId",u.getUserId());
		UserFundsInfoDO userFundsInfoDO = userFundsInfoDao.list(map).get(0);
		userFundsInfoDO.setFundsWithdrawMoney(userFundsInfoDO.getFundsWithdrawMoney().add(u.getWithdrawAmount()));
		int num = userFundsInfoDao.update(userFundsInfoDO);
		if(num > 0) {
			return userWithdrawDao.remove(withdrawId);
		}else{
			return 0;
		}
	}
	
	@Override
	public int batchRemove(Long[] withdrawIds){
		return userWithdrawDao.batchRemove(withdrawIds);
	}

	@Override
	@Transactional
	public int saveWithDraw(UserWithdrawDO userWithdraw, String userId) {
		Map<String,Object> map= new HashMap<>();
		map.put("userId",userId);
		UserFundsInfoDO userFundsInfoDO = userFundsInfoDao.list(map).get(0);
		userFundsInfoDO.setFundsWithdrawMoney(userFundsInfoDO.getFundsWithdrawMoney().subtract(userWithdraw.getWithdrawAmount()));
		int n = userFundsInfoDao.update(userFundsInfoDO);
		int m = 0;
		if(n > 0){
			m = userWithdrawDao.save(userWithdraw);
		}
		return m;
	}

}
